//
//  ReConnectBlueManager.m
//  BluetoothProject
//
//  Created by JianWei Chen on 16/9/5.
//  Copyright © 2016年 JianWei Chen. All rights reserved.
//

#import "DTCReConnectBlueManager.h"

#define DTCFindDeviceCircleTime 5.f

@interface DTCReConnectBlueManager ()

@property (strong, nonatomic) NSTimer *connectTimer;
@property (nonatomic, strong) NSMutableDictionary *reconnectDeviceMdic;//进行重连的设备

@end

@implementation DTCReConnectBlueManager

+ (DTCReConnectBlueManager *)sharedInstance
{
    static DTCReConnectBlueManager *static_manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        static_manager = [[DTCReConnectBlueManager alloc]init];
    });
    return static_manager;
}

- (instancetype)init
{
    if ([super init]) {
        [self connectTimer];
    }
    return self;
}

- (NSTimer *)connectTimer
{
    if (!_connectTimer) {
        _connectTimer = [NSTimer scheduledTimerWithTimeInterval:DTCFindDeviceCircleTime target:self selector:@selector(connectPeripheralAction:) userInfo:nil repeats:YES];
        [_connectTimer setFireDate:[NSDate distantFuture]];
    }
    return _connectTimer;
}

- (NSMutableDictionary *)reconnectDeviceMdic
{
    if (!_reconnectDeviceMdic) {
        _reconnectDeviceMdic = [[NSMutableDictionary alloc]init];
    }
    return _reconnectDeviceMdic;
}


- (void)connectPeripheralAction:(NSTimer *)timer
{
    for (DTCDeviceModel *device in self.reconnectDeviceMdic.allValues) {
        [self checkAndConnectToDevice:device];
    }
}

- (void)checkAndConnectToDevice:(DTCDeviceModel *)device
{
    if (device.currentPeripheral.state != CBPeripheralStateConnected) {
        [[DTCBluetoothManager shareInstance]connectDevice:device];
    }
}

- (void)startReconnectDevice:(DTCDeviceModel *)device
{
    if (device.peripheralUUID) {
        [self.reconnectDeviceMdic setValue:device forKey:device.peripheralUUID];
    }
    if (self.reconnectDeviceMdic.allValues.count != 0) {
        [self.connectTimer setFireDate:[NSDate distantPast]];
    }
}

- (void)stopReconnectDevice:(DTCDeviceModel *)device
{
    if (device.peripheralUUID) {
        [self.reconnectDeviceMdic removeObjectForKey:device.peripheralUUID];
        [[DTCBluetoothManager shareInstance]disconnectDevice:device];
    }
    if (self.reconnectDeviceMdic.allValues.count == 0) {
        [self.connectTimer setFireDate:[NSDate distantFuture]];
    }
}
@end
